<template>
    <div class="white-box-form">
        <el-form
            ref="ruleRef"
            :model="state.ruleForm"
            :rules="state.rules"
            label-width="120px"
            class="mt-20"
        >
            <!-- <el-form-item label="线路名称" prop="lineName">
                <el-input
                    v-model.trim="state.ruleForm.lineName"
                    clearable
                    placeholder="请输入线路名称"
                />
            </el-form-item> -->
            <el-form-item label="归属网点" prop="outletsSid">
                <selectLoadMore
                    v-model:selectValue="state.ruleForm.outletsSid"
                    v-model:options="state.outletsOptions"
                    v-model:needFilterOptions="state.needFilterOutletsOptions"
                    value="sid"
                    label="outletsName"
                    popperClass="outlet"
                    placeholder="请选择归属网点"
                    :apiFun="getOutletsOptions"
                />
            </el-form-item>
            <!-- 线路配置 -->
            <el-form-item label="线路配置" prop="config">
                <el-table
                    v-if="state.ruleForm.config?.length"
                    class="mb-10"
                    max-height="300"
                    :data="state.ruleForm.config"
                    :header-cell-style="{
                        background: '#F5F7FA',
                        textAlign: 'center',
                    }"
                    :cell-style="{
                        textAlign: 'center',
                    }"
                    border
                    element-loading-background="rgba(255, 255, 255, 0.6)"
                >
                    <el-table-column
                        prop="preserveName"
                        label="保藏类型"
                        min-width="120"
                    >
                    </el-table-column>
                    <el-table-column
                        prop="vehicleName"
                        label="运输方式"
                        min-width="120"
                    >
                    </el-table-column>
                    <el-table-column
                        prop="pricingName"
                        label="计价方式"
                        min-width="300"
                    >
                        <template #default="{ row }">
                            <p v-if="row.pricingType === 1">
                                {{ row.pricingName }}：{{
                                    fenToYuan(row.weightUnitPrice)
                                }}元/kg
                            </p>
                            <div v-if="row.pricingType === 2">
                                {{ row.pricingName }}：
                                <p
                                    v-for="item in row.sizeSaveDTO"
                                    :key="item.sid"
                                >
                                    {{ item.normsName }}：{{
                                        fenToYuan(item.unitPrice)
                                    }}元/个
                                </p>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="短运费" min-width="270">
                        <template #default="{ row }">
                            <!-- 无短运费 -->
                            <span v-if="row.shortType === 1">无</span>
                            <!-- 有短运费 -->
                            <template v-if="row.shortType === 0">
                                <span v-if="row.pricingType === 1"
                                    >免费重量：{{
                                        row.shortWeightSaveDTO.freeWeight
                                    }}kg，超出单位价：{{
                                        fenToYuan(
                                            row.shortWeightSaveDTO.unitPrice
                                        )
                                    }}元/kg</span
                                >
                                <span v-if="row.pricingType === 2"
                                    >免费体积：{{
                                        row.shortSizeSaveDTO.freeSize
                                    }}m³，超出单位价：{{
                                        fenToYuan(
                                            row.shortSizeSaveDTO.unitPrice
                                        )
                                    }}元/m³</span
                                >
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="操作"
                        width="120"
                        class-name="operation-nav"
                        fixed="right"
                    >
                        <template #default="{ $index }">
                            <el-button
                                link
                                type="primary"
                                @click="editConfig($index)"
                                >编辑</el-button
                            >
                            <el-button
                                link
                                type="primary"
                                @click="delConfig($index)"
                                >删除</el-button
                            >
                        </template>
                    </el-table-column>
                </el-table>
                <el-button
                    type="primary"
                    size="small"
                    plain
                    @click="addConfig"
                    icon="Plus"
                    >添加配置</el-button
                >
            </el-form-item>
            <el-form-item label="线路起点" prop="startDistrictCode">
                <p v-if="!state.startShow" class="mr-10">
                    {{ state.ruleForm.startDistrictInfo?.fullName }}
                </p>
                <el-cascader
                    v-if="state.startShow"
                    ref="startCascaderRef"
                    v-model="state.ruleForm.startDistrictCode"
                    class="mr-10"
                    filterable
                    :props="regionCodeProps"
                    clearable
                    placeholder="请选择线路起点"
                />
                <el-button
                    v-if="showStartBtn"
                    type="primary"
                    size="small"
                    plain
                    @click="changeSelectShow('start')"
                    >重新选择</el-button
                >
                <el-button
                    v-if="isEdit && state.startShow"
                    type="primary"
                    size="small"
                    plain
                    @click="cancelReSelect('start')"
                    >取消重选</el-button
                >
            </el-form-item>
            <el-form-item label="线路途径点" prop="routeDistrictCode">
                <div v-if="!state.routeShow">
                    <el-tag
                        v-for="item in state.ruleForm?.routeDistrictInfo"
                        :key="item.code"
                        class="mr-10"
                        type="info"
                        >{{ item.fullName }}</el-tag
                    >
                </div>
                <el-cascader
                    v-if="state.routeShow"
                    v-model="state.ruleForm.routeDistrictCode"
                    class="mr-10"
                    filterable
                    :props="regionCodeMultipleProps"
                    clearable
                    collapse-tags
                    placeholder="请选择线路途径点"
                />
                <el-button
                    v-if="showRouteBtn"
                    type="primary"
                    size="small"
                    plain
                    @click="changeSelectShow('route')"
                    >重新选择</el-button
                >
                <el-button
                    v-if="isEdit && state.routeShow"
                    type="primary"
                    size="small"
                    plain
                    @click="cancelReSelect('route')"
                    >取消重选</el-button
                >
            </el-form-item>
            <el-form-item label="线路终点" prop="endDistrictCode">
                <p v-if="!state.endShow" class="mr-10">
                    {{ state.ruleForm.endDistrictInfo?.fullName }}
                </p>
                <el-cascader
                    v-if="state.endShow"
                    ref="endCascaderRef"
                    v-model="state.ruleForm.endDistrictCode"
                    class="mr-10"
                    filterable
                    :props="regionCodeProps"
                    clearable
                    placeholder="请选择线路终点"
                />
                <el-button
                    v-if="showEndBtn"
                    type="primary"
                    size="small"
                    plain
                    @click="changeSelectShow('end')"
                    >重新选择</el-button
                >
                <el-button
                    v-if="isEdit && state.endShow"
                    type="primary"
                    size="small"
                    plain
                    @click="cancelReSelect('end')"
                    >取消重选</el-button
                >
            </el-form-item>
            <el-form-item label="预计耗时(天)" prop="estimatedDuration">
                <el-input-number
                    v-model="state.ruleForm.estimatedDuration"
                    :min="1"
                    :precision="0"
                    step-strictly
                />
            </el-form-item>
            <el-form-item label="提货方式" prop="deliveryType">
                <el-select
                    v-model="state.ruleForm.deliveryType"
                    placeholder="请选择提货方式"
                    clearable
                >
                    <el-option
                        v-for="item in state.deliveryTypeList"
                        :key="item.memberKey"
                        :label="item.memberName"
                        :value="item.memberKey"
                    />
                </el-select>
            </el-form-item>
            <el-form-item
                v-if="state.ruleForm.deliveryType === 0"
                label="提货员"
                prop="pickerSids"
            >
                <select-load-more
                    v-model:selectValue="state.ruleForm.pickerSids"
                    v-model:options="state.pickerOptions"
                    v-model:needFilterOptions="state.needFilterPickerOptions"
                    value="sid"
                    label="nickName"
                    multiple
                    placeholder="请选择提货员"
                    popper-class="picker-select"
                    :apiFun="getPickerOptions"
                />
            </el-form-item>
            <el-form-item
                v-if="state.ruleForm.deliveryType === 1"
                label="提货企业"
                prop="entdlvSid"
            >
                <select-load-more
                    v-model:selectValue="state.ruleForm.entdlvSid"
                    v-model:options="state.entdlvOptions"
                    v-model:needFilterOptions="state.needFilterEntdlvOptions"
                    value="entdlvSignCode"
                    label="entdlvName"
                    placeholder="请选择提货企业"
                    popper-class="entdlv-select"
                    :apiFun="getEntdlvOptions"
                />
            </el-form-item>

            <el-form-item label="备注" prop="note">
                <el-input
                    v-model.trim="state.ruleForm.note"
                    type="textarea"
                    maxlength="100"
                    :autosize="{ minRows: 2 }"
                    clearable
                    show-word-limit
                    placeholder="请输入备注"
                />
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-radio-group v-model="state.ruleForm.status">
                    <el-radio
                        v-for="item in state.statusList"
                        :key="item.memberKey"
                        :value="item.memberKey"
                        >{{ item.memberName }}</el-radio
                    >
                </el-radio-group>
            </el-form-item>
        </el-form>

        <div class="foot-btn">
            <el-button
                type="primary"
                :loading="state.form_loading"
                @click="submitForm(ruleRef)"
            >
                {{ isEdit ? "修改" : "添加" }}
            </el-button>
        </div>
        <go-back />
    </div>

    <el-dialog v-model="state.showConfigForm" title="线路配置">
        <el-form
            ref="configFormRef"
            :model="state.configForm"
            :rules="state.configRules"
            label-width="100px"
            class="mt-20"
        >
            <el-form-item label="保藏类型" prop="preserveSid">
                <selectLoadMore
                    v-model:selectValue="state.configForm.preserveSid"
                    v-model:options="state.preserveOptions"
                    v-model:needFilterOptions="state.needFilterPreserveOptions"
                    value="sid"
                    label="name"
                    popperClass="preserve"
                    placeholder="请选择保藏类型"
                    :apiFun="getPreserveOptions"
                />
            </el-form-item>
            <el-form-item label="运输方式" prop="vehicleSid">
                <el-select
                    v-model="state.configForm.vehicleSid"
                    placeholder="请选择运输方式"
                    clearable
                >
                    <el-option
                        v-for="item in state.vehicleOptions"
                        :key="item.sid"
                        :label="item.name"
                        :value="item.sid"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="计价方式" prop="pricingSid">
                <el-radio-group v-model="state.configForm.pricingSid">
                    <el-radio
                        v-for="item in state.pricingOptions"
                        :key="item.sid"
                        :value="item.sid"
                        >{{ item.name }}</el-radio
                    >
                </el-radio-group>
                <!-- <el-select
                    v-model="state.configForm.pricingSid"
                    placeholder="请选择计价方式"
                    clearable
                >
                    <el-option
                        v-for="item in state.pricingOptions"
                        :key="item.sid"
                        :label="item.name"
                        :value="item.sid"
                    />
                </el-select> -->
            </el-form-item>
            <!-- 选择计价方式后显示 -->
            <template v-if="state.configForm.pricingSid">
                <!-- 计价方式为按重量时显示 -->
                <el-form-item
                    v-if="configFormPricingType === 1"
                    label="单位价"
                    prop="weightUnitPrice"
                >
                    <el-input
                        v-model.trim="state.configForm.weightUnitPrice"
                        oninput="value=value.replace(/[^\d.]/g,'')"
                    />
                    <span class="ml-10">元/kg</span>
                </el-form-item>

                <!-- 计价方式为按体积时显示 -->
                <el-form-item
                    v-if="configFormPricingType === 2"
                    label="装箱规格"
                    prop="sizeSaveDTO"
                >
                    <el-table
                        v-if="state.configForm.sizeSaveDTO?.length"
                        :data="state.configForm.sizeSaveDTO"
                        class="mb-10"
                        max-height="200"
                        :header-cell-style="{
                            background: '#F5F7FA',
                            textAlign: 'center',
                        }"
                        :cell-style="{
                            textAlign: 'center',
                        }"
                        border
                    >
                        <el-table-column
                            prop="normsName"
                            label="规格"
                            min-width="200"
                        >
                        </el-table-column>
                        <el-table-column
                            prop="unitPrice"
                            label="单位价(元/个)"
                            min-width="100"
                        >
                            <template #default="{ row }">
                                {{ fenToYuan(row.unitPrice) }}
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="操作"
                            width="120"
                            class-name="operation-nav"
                            fixed="right"
                        >
                            <template #default="{ $index }">
                                <el-button
                                    link
                                    type="primary"
                                    @click="editNorms($index)"
                                    >编辑</el-button
                                >
                                <el-button
                                    link
                                    type="primary"
                                    @click="delNorms($index)"
                                    >删除</el-button
                                >
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-button
                        type="primary"
                        plain
                        @click="addNorms"
                        icon="Plus"
                        size="small"
                        >添加装箱规格</el-button
                    >
                </el-form-item>

                <el-form-item label="有无短运费" prop="shortType">
                    <el-switch
                        v-model="state.configForm.shortType"
                        inline-prompt
                        :active-value="0"
                        :inactive-value="1"
                        active-text="有"
                        inactive-text="无"
                    />
                </el-form-item>
                <!-- 有短运费时显示 -->
                <template v-if="state.configForm.shortType === 0">
                    <!-- 按重量 -->
                    <template v-if="configFormPricingType === 1">
                        <el-form-item
                            label="免费重量"
                            prop="shortWeightSaveDTO.freeWeight"
                        >
                            <el-input
                                v-model.trim="
                                    state.configForm.shortWeightSaveDTO
                                        .freeWeight
                                "
                                oninput="value=value.replace(/[^\d.]/g,'')"
                            />
                            <span class="ml-10">kg</span>
                        </el-form-item>
                        <el-form-item
                            label="超出单位价"
                            prop="shortWeightSaveDTO.unitPrice"
                        >
                            <el-input
                                v-model.trim="
                                    state.configForm.shortWeightSaveDTO
                                        .unitPrice
                                "
                                oninput="value=value.replace(/[^\d.]/g,'')"
                            />
                            <span class="ml-10">元/kg</span>
                        </el-form-item>
                    </template>
                    <!-- 按体积 -->
                    <template v-if="configFormPricingType === 2">
                        <el-form-item
                            label="免费体积"
                            prop="shortSizeSaveDTO.freeSize"
                        >
                            <el-input
                                v-model.trim="
                                    state.configForm.shortSizeSaveDTO.freeSize
                                "
                                oninput="value=value.replace(/[^\d.]/g,'')"
                            />
                            <span class="ml-10">m³</span>
                        </el-form-item>
                        <el-form-item
                            label="超出单位价"
                            prop="shortSizeSaveDTO.unitPrice"
                        >
                            <el-input
                                v-model.trim="
                                    state.configForm.shortSizeSaveDTO.unitPrice
                                "
                                oninput="value=value.replace(/[^\d.]/g,'')"
                            />
                            <span class="ml-10">元/m³</span>
                        </el-form-item>
                    </template>
                </template>
            </template>
            <el-form-item>
                <el-button
                    type="primary"
                    @click="submitConfigForm(configFormRef)"
                >
                    确认
                </el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <el-dialog v-model="state.showNormsForm" title="装箱规格" width="400">
        <el-form
            ref="normsFormRef"
            :model="state.normsForm"
            :rules="state.normsRules"
            label-position="top"
        >
            <el-form-item label="装箱规格" prop="normsSid">
                <select-load-more
                    class="!w-100%"
                    v-model:selectValue="state.normsForm.normsSid"
                    v-model:options="state.normsOptions"
                    v-model:needFilterOptions="state.needFilterNormsOptions"
                    value="sid"
                    label="normsName"
                    placeholder="请选择装箱规格"
                    popper-class="norms"
                    :apiFun="getNormsOptions"
                >
                    <template #header>
                        <div
                            class="flex justify-between pl-10 pr-20 color-blueGray"
                        >
                            <span>名称</span>
                            <span>长 * 宽 * 高(m)</span>
                        </div>
                    </template>
                    <template #option="{ option }">
                        <span class="float-left">{{ option.normsName }}</span>
                        <span class="float-right"
                            >{{ option.normsLength }} * {{ option.normsWide }} *
                            {{ option.normsHigh }}</span
                        >
                    </template>
                </select-load-more>
            </el-form-item>
            <el-form-item label="单位价(元/个)" prop="unitPrice">
                <el-input
                    v-model.trim="state.normsForm.unitPrice"
                    oninput="value=value.replace(/[^\d.]/g,'')"
                    class="!w-100%"
                />
            </el-form-item>
            <el-form-item>
                <el-button
                    type="primary"
                    class="w-100% mt-10 mb--10"
                    @click="submitNormsForm(normsFormRef)"
                >
                    确认
                </el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script setup>
import { inject, ref, onMounted, reactive, computed, nextTick } from "vue";
import { useRouter, useRoute } from "vue-router";
import GoBack from "@components/GoBack.vue";

import selectLoadMore from "@/components/selectLoadMore.vue";
import {
    getLineDetail,
    addLine,
    editLine,
    getLineEntdlvs,
    getLineConfigs,
    getLineUsers,
} from "@/apis/enterprise/line.js";
import { getEntdlvs } from "@/apis/enterprise/entdlv.js";
import { getPreserves } from "@/apis/enterprise/preserve.js";
import { getVehiclesAll } from "@/apis/enterprise/vehicle.js";
import { getNorms, getNormsAll } from "@/apis/enterprise/norm.js";
import { getOrderConfigs } from "@/apis/order/config.js";
import { getAreas } from "@/apis/common.js";
import { getOutlets, getOutletDetail } from "@/apis/outlet/outlet.js";
import { getTakePickers } from "@/apis/user/user.js";
import { fenToYuan, yuanToFen } from "@/assets/common/utils.js";
import { useDictStore } from "@stores/dict.js";

const dictStore = useDictStore();
dictStore.getDictMembers("data_status").then((res) => (state.statusList = res));
dictStore
    .getDictMembers("line_delivery_type")
    .then((res) => (state.deliveryTypeList = res));

const router = useRouter();
const route = useRoute();

const $message = inject("$message");

const sid = route.query.sid;
const isEdit = ref(false);
// 整个表单
const form_loading = ref(false);
const ruleRef = ref(null);
// 线路配置表单
const configFormRef = ref(null);
// 装箱规格表单
const normsFormRef = ref(null);
// 省市区选择
const startCascaderRef = ref(null);
const endCascaderRef = ref(null);
const validateConfig = (_, value, callback) => {
    if (!value.length) {
        callback(new Error("请添加线路配置"));
    } else {
        // 校验线路配置
        value.forEach((item, index) => {
            if (!item.preserveSid) {
                callback(new Error(`请选择线路配置【${index + 1}】的保藏类型`));
            }
            if (!item.pricingSid) {
                callback(new Error(`请选择线路配置【${index + 1}】的计价方式`));
            }
            if (!item.vehicleSid) {
                callback(new Error(`请选择线路配置【${index + 1}】的运输方式`));
            }
        });
        callback();
    }
};
const state = reactive({
    statusList: [],
    deliveryTypeList: [],
    ruleForm: {
        config: [
            // {
            // index: 0, // 线路配置表格 row-key
            // preserveSid: "",
            // pricingSid: "",
            // shortSizeSaveDTO: {
            //     freeSize: 0,
            //     unitPrice: 0
            // },
            // shortType: 0,
            // shortWeightSaveDTO: {
            //     freeWeight: 0,
            //     unitPrice: 0
            // },
            // sizeSaveDTO: [
            //     // {
            //     // index: 0, // 装箱规格配置表格 row-key
            //     // normsSid: "",
            //     // unitPrice: 0
            //     // }
            // ],
            // vehicleSid: "",
            // weightUnitPrice: "",
            // pricingType: 1 // 计价方式  1 按重量 2 按体积
            // }
        ],
        deliveryType: null,
        endDistrictCode: null,
        endLatitude: null,
        endLongitude: null,
        entdlvSid: null,
        estimatedDuration: null,
        lineName: null,
        note: null,
        outletsSid: null,
        pickerSids: [],
        routeDistrictCode: null, // 途径点
        startDistrictCode: null, // 起点
        startLatitude: null,
        startLongitude: null,
        status: 0,
        startDistrictInfo: {
            fullName: null,
        },
        endDistrictInfo: {
            fullName: null,
        },
        routeDistrictInfo: [],
    },
    rules: {
        lineName: [
            { required: true, message: "请输入线路名称", trigger: "blur" },
        ],
        outletsSid: [
            { required: true, message: "请选择归属网点", trigger: "blur" },
        ],
        config: [
            { required: true, validator: validateConfig, trigger: "blur" },
        ],
        startDistrictCode: [
            { required: true, message: "请选择线路起点", trigger: "blur" },
        ],
        // routeDistrictCode: [
        //     { required: true, message: "请选择线路途径点", trigger: "blur" },
        // ],
        endDistrictCode: [
            { required: true, message: "请选择线路终点", trigger: "blur" },
        ],
        estimatedDuration: [
            { required: true, message: "请输入预计耗时", trigger: "blur" },
        ],
        deliveryType: [
            { required: true, message: "请选择提货方式", trigger: "blur" },
        ],
        entdlvSid: [
            { required: true, message: "请选择提货企业", trigger: "blur" },
        ],
        pickerSids: [
            { required: true, message: "请选择提货员", trigger: "blur" },
        ],
    },
    showConfigForm: false,
    configForm: {
        preserveSid: null,
        pricingSid: null,
        shortSizeSaveDTO: {
            freeSize: "",
            unitPrice: "",
        },
        shortType: 1,
        shortWeightSaveDTO: {
            freeWeight: "",
            unitPrice: "",
        },
        sizeSaveDTO: [
            // {
            // normsSid: "",
            // unitPrice: 0
            // }
        ],
        vehicleSid: null,
        weightUnitPrice: null,
    },
    configRules: {
        preserveSid: [
            { required: true, message: "请选择保藏类型", trigger: "blur" },
        ],
        vehicleSid: [
            { required: true, message: "请选择运输方式", trigger: "blur" },
        ],
        pricingSid: [
            { required: true, message: "请选择计价方式", trigger: "blur" },
        ],
        weightUnitPrice: [
            { required: true, message: "请输入单位价", trigger: "blur" },
        ],
        "shortWeightSaveDTO.freeWeight": [
            {
                required: true,
                message: "请输入短运费免费重量",
                trigger: "blur",
            },
        ],
        "shortWeightSaveDTO.unitPrice": [
            {
                required: true,
                message: "请输入短运费超出单位价",
                trigger: "blur",
            },
        ],
        "shortSizeSaveDTO.freeSize": [
            {
                required: true,
                message: "请输入短运费免费体积",
                trigger: "blur",
            },
        ],
        "shortSizeSaveDTO.unitPrice": [
            {
                required: true,
                message: "请输入短运费超出单位价",
                trigger: "blur",
            },
        ],
        sizeSaveDTO: [
            {
                required: true,
                message: "请添加装箱规格",
                trigger: "blur",
            },
        ],
    },
    showNormsForm: false,
    normsForm: {
        normsSid: null,
        unitPrice: "",
    },
    normsRules: {
        normsSid: [
            { required: true, message: "请选择装箱规格", trigger: "blur" },
        ],
        unitPrice: [
            { required: true, message: "请输入单位价", trigger: "blur" },
        ],
    },
    startShow: true,
    routeShow: true,
    endShow: true,
    outletsOptions: [],
    needFilterOutletsOptions: [],
    preserveOptions: [],
    needFilterPreserveOptions: [],
    vehicleOptions: [],
    pricingOptions: [],
    normsOptions: [],
    needFilterNormsOptions: [],
    pickerOptions: [],
    needFilterPickerOptions: [],
    entdlvOptions: [],
    needFilterEntdlvOptions: [],
    areaList: [],
});

// 1 按重量 2 按体积
const configFormPricingType = computed(() => {
    if (state.configForm.pricingSid) {
        return state.pricingOptions.find(
            (item) => state.configForm.pricingSid === item.sid
        ).value;
    } else {
        return null;
    }
});

const showStartBtn = computed(() => {
    return (
        isEdit.value &&
        !state.startShow &&
        state.ruleForm.startDistrictInfo?.fullName
    );
});

const showRouteBtn = computed(() => {
    return (
        isEdit.value &&
        !state.routeShow &&
        state.ruleForm?.routeDistrictInfo.length
    );
});

const showEndBtn = computed(() => {
    return (
        isEdit.value &&
        !state.endShow &&
        state.ruleForm.endDistrictInfo?.fullName
    );
});

onMounted(() => {
    if (/Edit$/.test(route.name)) {
        isEdit.value = true;
        getDetail();
    }
    getVehicleOptions();
    getPricingOptions();
});

const getDetail = async () => {
    const res = await getLineDetail({ sid });
    if (res.data.code == 200) {
        state.ruleForm = res.data.data;
        // 处理线路起点 途径点 终点 信息
        const { startDistrictInfo, routeDistrictInfo, endDistrictInfo } =
            state.ruleForm;
        state.startShow = false;
        state.ruleForm.startDistrictCode = startDistrictInfo.code;
        state.routeShow = false;
        state.ruleForm.routeDistrictCode = routeDistrictInfo.map(
            (item) => item.code
        );
        state.endShow = false;
        state.ruleForm.endDistrictCode = endDistrictInfo.code;
        // 网点
        if (state.ruleForm.outletsSid) {
            getOutletsDetail(state.ruleForm.outletsSid).then((res) => {
                state.outletsOptions.push(res);
                state.needFilterOutletsOptions.push(res);
            });
        }
        // 线路配置
        getConfig();
        switch (state.ruleForm.deliveryType) {
            case 0:
                // 提货员提货
                await getUser();
                break;
            case 1:
                // 提货企业提货
                await getEntdlv();
                break;
        }
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const getAreaList = async (parentCode = 0) => {
    const res = await getAreas({ parentCode });
    if (res.data.code == 200) {
        res.data.data.forEach((item) => {
            if (item.level === "province") {
                item.disabled = true;
            }
            if (item.level === "district") {
                item.leaf = true;
            }
        });
        state.areaList = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 级联选择器配置
const regionCodeProps = {
    emitPath: false,
    lazy: true,
    value: "code",
    label: "name",
    checkStrictly: true,
    lazyLoad(node, resolve) {
        const { value } = node;
        getAreaList(value).then(() => {
            resolve(state.areaList);
        });
    },
};

// 多选
const regionCodeMultipleProps = {
    ...regionCodeProps,
    multiple: true,
};

// 当线路途径点选中市级又选中该市级下的区级时，去除该市级
const filterSelectedCityCode = () => {
    const { routeDistrictCode } = state.ruleForm;
    const cities = routeDistrictCode.filter(
        (item) => String(item).length === 4
    );
    // 如果选择了当前节点的子级，则不选择当前节点
    cities.forEach((city) => {
        const districts = routeDistrictCode.find((item) => {
            const stringItem = String(item);
            const stringCity = String(city);
            return (
                stringItem.length > 4 && stringItem.slice(0, 4) === stringCity
            );
        });
        if (districts) {
            // 选中市级又选中该市级下的区级时，去除该市级
            const index = routeDistrictCode.findIndex((item) => item === city);
            if (index >= 0) {
                routeDistrictCode.splice(index, 1);
            }
        }
    });
};

const changeSelectShow = (key) => {
    state[key + "Show"] = true;
    if (key === "route") {
        state.ruleForm.routeDistrictCode = [];
    } else {
        state.ruleForm[key + "DistrictCode"] = null;
    }
};

const cancelReSelect = (key) => {
    state[key + "Show"] = false;
    if (key === "route") {
        state.ruleForm.routeDistrictCode = state.ruleForm.routeDistrictInfo.map(
            (item) => item.code
        );
    } else {
        state.ruleForm[key + "DistrictCode"] =
            state.ruleForm[key + "DistrictInfo"].code;
    }
};

// 获取网点
const getOutletsOptions = async (params) => {
    const res = await getOutlets({
        ...params,
        outletsName: params.keyword,
    });
    if (res.data.code == 200) {
        return res;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 获取网点详情
const getOutletsDetail = async (sid) => {
    const res = await getOutletDetail({ sid });
    if (res.data.code == 200) {
        return res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 获取保藏类型
const getPreserveOptions = async (params) => {
    const res = await getPreserves({
        ...params,
        preserveName: params.keyword,
    });
    if (res.data.code == 200) {
        res.data.data.records = res.data.data.records.map((item) => {
            return {
                sid: item.sid,
                name: item.preserveName,
            };
        });
        return res;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const getVehicleOptions = async () => {
    const res = await getVehiclesAll();
    if (res.data.code == 200) {
        state.vehicleOptions = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 获取计价方式
const getPricingOptions = async () => {
    const res = await getOrderConfigs({ type: 3 });
    if (res.data.code == 200) {
        state.pricingOptions = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 获取装箱规格
// const getNormsOptions = async () => {
//     const res = await getNormsAll();
//     if (res.data.code == 200) {
//         state.normsOptions = res.data.data;
//     } else {
//         $message({ message: res.data.msg, type: "error" });
//     }
// };

const getNormsOptions = async (params) => {
    const res = await getNorms({
        ...params,
        normsName: params.keyword,
    });
    if (res.data.code == 200) {
        return res;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 获取提货员
const getPickerOptions = async (params) => {
    const res = await getTakePickers({
        ...params,
        userName: params.keyword,
    });
    if (res.data.code == 200) {
        return res;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const getEntdlvOptions = async (params) => {
    const res = await getEntdlvs({
        ...params,
        entdlvName: params.keyword,
    });
    if (res.data.code == 200) {
        return res;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 根据线路ID查询线路配置信息
const getConfig = async () => {
    const res = await getLineConfigs({ sid });
    if (res.data.code == 200) {
        state.ruleForm.config = res.data.data;
        state.ruleForm.config.forEach((item) => {
            const pricingType = item.pricingValue;
            item.pricingType = pricingType;

            // 短运费 按重量
            // item.shortWeightSaveDTO = {
            //     freeWeight: "",
            //     unitPrice: "",
            // };
            // 短运费 按体积
            // item.shortSizeSaveDTO = {
            //     freeSize: "",
            //     unitPrice: "",
            // };

            if (pricingType === 1) {
                // 按重量
                if (item.shortType === 0) {
                    // 含短运费
                    item.shortWeightSaveDTO = {
                        freeWeight: item.freeWeight,
                        unitPrice: item.weightShortPrice,
                    };
                }
            }
            if (pricingType === 2) {
                // 按体积
                if (item.shortType === 0) {
                    // 含短运费
                    item.shortSizeSaveDTO = {
                        freeSize: item.freeSize,
                        unitPrice: item.sizeShortPrice,
                    };
                }
                // 装箱规格
                item.sizeSaveDTO = item.configSize.map(
                    ({ norms, sizeUnitPrice }) => {
                        return {
                            normsSid: norms.sid,
                            normsName: `${norms.normsName}(${norms.normsLength} * ${norms.normsWide} * ${norms.normsHigh})`,
                            unitPrice: sizeUnitPrice,
                        };
                    }
                );
            }
        });
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 根据线路ID查询线路绑定的提货企业
const getEntdlv = async () => {
    const res = await getLineEntdlvs({ sid });
    if (res.data.code == 200) {
        const entdlv = res.data.data;
        state.ruleForm.entdlvSid = entdlv.entdlvSignCode;
        state.entdlvOptions.push(entdlv);
        state.needFilterEntdlvOptions.push(entdlv);
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 根据线路ID查询线路绑定的提货员
const getUser = async () => {
    const res = await getLineUsers({ sid });
    if (res.data.code == 200) {
        const users = res.data.data;
        state.ruleForm.pickerSids = [];
        users.forEach((item) => {
            state.ruleForm.pickerSids.push(item.sid);
            state.pickerOptions.push(item);
            console.log(item);
            state.needFilterPickerOptions.push(item);
        });
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

let selectedConfigIndex = null;
// 添加线路配置
const addConfig = () => {
    selectedConfigIndex = null;
    state.showConfigForm = true;
    nextTick(() => configFormRef.value.resetFields());
    state.configForm.sizeSaveDTO = [];
};

// 编辑线路配置
const editConfig = (index) => {
    selectedConfigIndex = index;
    state.showConfigForm = true;
    nextTick(() => {
        const form = JSON.parse(JSON.stringify(state.ruleForm.config[index]));

        const {
            preserveName,
            preserveSid,
            pricingType,
            shortSizeSaveDTO,
            shortType,
            shortWeightSaveDTO,
            weightUnitPrice,
        } = form;
        // 添加保藏类型过滤选项
        const preserve = { sid: preserveSid, name: preserveName };
        state.preserveOptions = [preserve];
        state.needFilterPreserveOptions = [preserve];
        // 按重量
        if (pricingType === 1) {
            form.weightUnitPrice = fenToYuan(weightUnitPrice);
        }
        // 短运费 按重量
        form.shortWeightSaveDTO = {
            freeWeight: "",
            unitPrice: "",
        };
        // 短运费 按体积
        form.shortSizeSaveDTO = {
            freeSize: "",
            unitPrice: "",
        };
        // 有短运费
        if (shortType === 0) {
            switch (pricingType) {
                case 1:
                    // 按重量
                    form.shortWeightSaveDTO.freeWeight = Number(
                        shortWeightSaveDTO.freeWeight
                    );
                    form.shortWeightSaveDTO.unitPrice = fenToYuan(
                        shortWeightSaveDTO.unitPrice
                    );
                    break;
                case 2:
                    // 体积
                    form.shortSizeSaveDTO.freeSize = Number(
                        shortSizeSaveDTO.freeSize
                    );
                    form.shortSizeSaveDTO.unitPrice = fenToYuan(
                        shortSizeSaveDTO.unitPrice
                    );
                    break;
            }
        }
        state.configForm = form;
    });
};

// 删除线路配置
const delConfig = (index) => {
    state.ruleForm.config.splice(index, 1);
};

// 提交线路配置表单
const submitConfigForm = (formEl) => {
    if (!formEl) return;
    formEl.validate(async (valid, fields) => {
        if (valid) {
            const {
                preserveSid,
                pricingSid,
                shortSizeSaveDTO,
                shortType,
                shortWeightSaveDTO,
                vehicleSid,
                weightUnitPrice,
            } = state.configForm;
            const pricingType = configFormPricingType.value;
            const form = {
                ...JSON.parse(JSON.stringify(state.configForm)),
                pricingType,
                preserveName: state.preserveOptions.find(
                    (item) => item.sid === preserveSid
                ).name,
                pricingName: state.pricingOptions.find(
                    (item) => item.sid === pricingSid
                ).name,
                vehicleName: state.vehicleOptions.find(
                    (item) => item.sid === vehicleSid
                ).name,
            };
            // 按重量
            if (pricingType === 1) {
                form.weightUnitPrice = yuanToFen(weightUnitPrice);
            }
            // 有短运费
            if (shortType === 0) {
                switch (pricingType) {
                    case 1:
                        // 按重量
                        form.shortWeightSaveDTO.freeWeight = Number(
                            shortWeightSaveDTO.freeWeight
                        );
                        form.shortWeightSaveDTO.unitPrice = yuanToFen(
                            shortWeightSaveDTO.unitPrice
                        );
                        delete form.shortSizeSaveDTO;
                        delete form.sizeSaveDTO;
                        break;
                    case 2:
                        // 体积
                        form.shortSizeSaveDTO.freeSize = Number(
                            shortSizeSaveDTO.freeSize
                        );
                        form.shortSizeSaveDTO.unitPrice = yuanToFen(
                            shortSizeSaveDTO.unitPrice
                        );
                        delete form.shortWeightSaveDTO;
                        delete form.weightUnitPrice;
                        break;
                }
            }
            // 无短运费
            if (shortType === 1) {
                delete form.shortSizeSaveDTO;
                delete form.shortWeightSaveDTO;
                switch (pricingType) {
                    case 1:
                        // 按重量
                        delete form.sizeSaveDTO;
                        break;
                    case 2:
                        // 按体积
                        delete form.weightUnitPrice;
                        break;
                }
                if (pricingType === 2) {
                }
            }
            if (selectedConfigIndex !== null) {
                // 编辑
                state.ruleForm.config[selectedConfigIndex] = form;
            } else {
                // 新增
                state.ruleForm.config.push(form);
            }
            state.showConfigForm = false;
        }
    });
};

let selectedNormsIndex = null;
// 添加装箱规格
const addNorms = () => {
    selectedNormsIndex = null;
    state.showNormsForm = true;
    nextTick(() => normsFormRef.value.resetFields());
};

// 编辑装箱规格
const editNorms = (index) => {
    selectedNormsIndex = index;
    state.showNormsForm = true;
    nextTick(() => {
        const form = JSON.parse(
            JSON.stringify(state.configForm.sizeSaveDTO[index])
        );
        form.unitPrice = fenToYuan(form.unitPrice);
        state.normsForm = form;
    });
};

// 删除装箱规格
const delNorms = (index) => {
    state.configForm.sizeSaveDTO.splice(index, 1);
};

// 提交装箱规格表单
const submitNormsForm = (formEl) => {
    if (!formEl) return;
    formEl.validate(async (valid, fields) => {
        if (valid) {
            const { normsSid, unitPrice } = state.normsForm;
            const form = {
                ...state.normsForm,
                normsName: "",
                unitPrice: yuanToFen(unitPrice),
            };
            const norms = state.normsOptions.find(
                (item) => item.sid === normsSid
            );
            form.normsName = `${norms.normsName}(${norms.normsLength} * ${norms.normsWide} * ${norms.normsHigh})`;
            if (selectedNormsIndex !== null) {
                // 编辑
                state.configForm.sizeSaveDTO[selectedNormsIndex] = form;
            } else {
                // 新增
                if (!state.configForm.sizeSaveDTO)
                    state.configForm.sizeSaveDTO = [];
                state.configForm.sizeSaveDTO.push(form);
            }
            state.showNormsForm = false;
        }
    });
};

// 提交表单
const submitForm = (formEl) => {
    if (!formEl) return;
    formEl.validate(async (valid, fields) => {
        if (valid) {
            form_loading.value = true;
            filterSelectedCityCode();
            // 起点 经纬度
            if (startCascaderRef.value) {
                const start = startCascaderRef.value.getCheckedNodes()[0].data;
                state.ruleForm.startLatitude = start.latitude;
                state.ruleForm.startLongitude = start.longitude;
            }
            // 终点 经纬度
            if (endCascaderRef.value) {
                const end = endCascaderRef.value.getCheckedNodes()[0].data;
                state.ruleForm.endLatitude = end.latitude;
                state.ruleForm.endLongitude = end.longitude;
            }
            let res = null;
            if (isEdit.value) {
                res = await editLine(state.ruleForm);
            } else {
                res = await addLine(state.ruleForm);
            }
            form_loading.value = false;
            if (res.data.code == 200) {
                $message({
                    message: isEdit.value ? "修改成功" : "添加成功",
                    type: "success",
                });
                router.back();
            } else {
                $message({ message: res.data.msg, type: "error" });
            }
        }
    });
};
</script>

<style scoped lang="less"></style>
